import { message } from "ant-design-vue";
import { process_get, process_update } from "@/api/process";
import { storeToRefs } from "pinia";
import { useCategoryStore } from "@/store/category";
import { script_execute } from "@/api/script";
import {
  get_site_script_data,
  get_global_config_by_key,
} from "@/utils/storage";
import { syncCategory } from "@/api/hc_category";

const categoryStore = useCategoryStore();
const { selectedCategory } = storeToRefs(categoryStore);

// #region => Process 操作相关 >>>>>>>>>

// 获取当前进程数据
export async function fetch_process_data(no_warn = false) {
  try {
    const res = await process_get(selectedCategory.value.id);
    console.log("fetch_process_data", res);
    return JSON.parse(res.data.find((item) => item.jobStep === "START").data);
  } catch (err) {
    if (!no_warn) {
      message.error(`获取当前进程数据失败: ${err}`);
    }
    return null;
  }
}

// 更新当前进程数据
export async function update_process_data(process_data) {
  try {
    const res = await process_update(selectedCategory.value.id, process_data);
    return true;
  } catch (err) {
    message.error(`更新当前步骤数据失败: ${err}`);
  }
}

// 更新当前步骤数据
export async function update_step_data(
  process_step,
  process_data,
  step_data,
  extra_data = null
) {
  const existing_process = process_data.find((step) => {
    return step.process === process_step;
  });
  if (existing_process) {
    existing_process.data = step_data;
    existing_process.extra_data = extra_data;
  } else {
    process_data.push({
      process: process_step,
      data: step_data,
      extra_data: extra_data,
    });
  }
  try {
    const res = await process_update(selectedCategory.value.id, process_data);
    return true;
  } catch (err) {
    message.error(`更新当前步骤数据失败: ${err}`);
  }
}

// 获取指定步骤的数据
export function get_process_step_data(process_data, step_name) {
  return process_data?.find((item) => item.process === step_name);
}

// 克隆指定步骤的数据
export function clone_process_step_data(process_data, step_name) {
  return JSON.parse(
    JSON.stringify(process_data.find((item) => item.process === step_name))
  );
}

// #endregion Process 操作相关 <<<<<<<<<

// #region => Process 数据提取相关 >>>>>>>>>

// 获取站点数据
export function get_site_data(process_data) {
  return get_process_step_data(process_data, "START").data.mapping_categories;
}

// 获取原始站点类目数据
export function get_raw_condition_map(process_data) {
  return get_process_step_data(process_data, "START").extra_data.condition_map;
}

// 获取站点类目数据
export function get_condition_map(process_data, site_code, category_code) {
  return get_process_step_data(process_data, "START").extra_data.condition_map[
    `${site_code}:${category_code}`
  ];
}

// 获取基准站点代码
export function get_baseline_site_code(process_data) {
  return get_process_step_data(process_data, "START").extra_data
    .baseline_site_code;
}

// 获取指定类别的条件数据
export function get_condition_map_by_class(process_data, class_name) {
  return get_process_step_data(process_data, "CONDITION_DIV").data[class_name];
}

// 克隆指定类别的条件数据
export function clone_condition_map_by_class(process_data, class_name) {
  return clone_process_step_data(process_data, "CONDITION_DIV").data[
    class_name
  ];
}

// 克隆站点数据
export function clone_site_data(process_data) {
  return clone_process_step_data(process_data, "START").data.mapping_categories;
}

// 获取站点类目的条件数据
export async function fetch_condition_data(
  website_code,
  category_id,
  category_code
) {
  try {
    function show(_item) {
      console.log(`debug->show_item`,_item)
      return _item
    }
    console.log(`output->fetch_condition_data req`, website_code, category_id, category_code);
    let script_id = show(await get_site_script_data(website_code))?.scripts.find(
      (item) => item.description === "CONDITION_EXTRACT"
    ).id;
    const res = await script_execute(script_id, [
      {
        dataType: "string",
        name: "website_code",
        paramId: "",
        paramType: 1,
        value: website_code,
      },
      {
        dataType: "int",
        name: "category_id",
        paramId: "",
        paramType: 1,
        value: parseInt(category_id),
      },
    ]);
    console.log(`output->fetch_condition_data res`, res);
    return JSON.parse(res.data).map((item) => {
      item.site_code = website_code; // 补充站点编码字段
      item.category_id = category_id; // 补充类目 ID 字段
      item.category_code = category_code; // 补充类目编码字段
      return item;
    });
  } catch (err) {
    message.error(`获取站点搜索条件数据失败: ${err}`);
  }
}

// #endregion Process 数据提取相关 <<<<<<<<<

// #region => 对齐结果数据处理相关 >>>>>>>>>

// 执行数据表格生成
export async function excel_generate(process_data) {
  let script_id = (await get_global_config_by_key("GLOBAL_EXCEL_GENERATE"))
    ?.extraInfo;
  return await script_execute(script_id, [
    {
      dataType: "string",
      name: "json_object_str",
      paramId: "",
      paramType: 1,
      value: JSON.stringify(process_data),
    },
  ]);
}

// 执行 SQL 生成
export async function sql_generate(excel_url) {
  let script_id = (await get_global_config_by_key("GLOBAL_SQL_GENERATE"))
    ?.extraInfo;
  return await script_execute(script_id, [
    {
      dataType: "string",
      name: "file_name",
      paramId: "",
      paramType: 1,
      value: excel_url,
    },
  ]);
}

// SQL 执行
export async function sql_execute(sql_strings_txt) {
  let script_id = (await get_global_config_by_key("GLOBAL_SQL_EXECUTE"))
    ?.extraInfo;
  return await script_execute(script_id, [
    {
      dataType: "string",
      name: "sql_strings_txt",
      paramId: "",
      paramType: 1,
      value: sql_strings_txt,
    },
  ]);
}

// 同步对齐结果
export async function sync_align_result() {
  try {
    return await syncCategory(selectedCategory.value.id);
  } catch (err) {
    message.error(err?.message ?? '同步数据时出现未知错误')
  }
}

// #endregion 对齐结果数据处理相关 <<<<<<<<<

// #region => 编辑进度处理相关 >>>>>>>>>

// 删除不同组搜索条件
export function drop_diff_condition(process_data, condition_item) {
  const step_data = get_process_step_data(process_data, "DIFF_MERGE");

  if (step_data?.data?.diff_conditions) {
    const diff_conditions = step_data.data.diff_conditions;
    for (let site_key in diff_conditions) {
      if (site_key === condition_item.site_code) {
        diff_conditions[site_key] = diff_conditions[site_key].filter(
          (item) => item.condition_code !== condition_item.condition_code
        );
      }
    }
  }

  return process_data;
}

// 删除拆解组搜索条件
export function drop_tear_condition(process_data, condition_item) {
  const step_data = get_process_step_data(process_data, "TEARDOWN");

  console.log(`output->condition_item`, condition_item);
  if (step_data?.data?.tear_conditions) {
    step_data.data.tear_conditions = step_data.data.tear_conditions.filter(
      (item) =>
        item.condition_code !== condition_item.condition_code ||
        item.site_code !== condition_item.site_code
    );
  }

  return process_data;
}

// #endregion 编辑进度处理相关 <<<<<<<<<
